package face.pay.common.enterprise.service.impl;

import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.sdk.OSSUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import face.pay.common.enterprise.service.IStoreInfoBaseService;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.ResultMessage;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Auther: zkj
 * @Date: 2019/7/15 09:57
 * @Description:
 */
@Service
@Slf4j
public class StoreInfoBaseServiceImpl implements IStoreInfoBaseService {


    @Autowired
    private StoreInfoDao storeInfoDao;

    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    private StoreMaterialInfoDao storeMaterialInfoDao;

    @Override
    public PageData<StoreInfo> queryPage(StoreInfo storeInfo, PageParam pageParam) {

        PageHelper.startPage(pageParam.getPageNo(),pageParam.getPageSize());

        List<StoreInfo> storeInfos = this.storeInfoDao.queryByUserId(storeInfo);

        PageInfo<StoreInfo> pageInfo = new PageInfo <StoreInfo>(storeInfos);

        PageData<StoreInfo> pageData = new PageData<StoreInfo>(pageInfo.getTotal(),storeInfos);

        return pageData;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage modifyInfo(StoreInfo storeInfo, UserInfo loginUser) {

        Integer userId = loginUser.getId();

        EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(userId);
        if(enterpriseInfo!=null){

            Integer id = storeInfo.getId();
            if(id==null){
                storeInfo.setCreatedBy(userId);
                storeInfo.setUserId(userId);
                storeInfo.setOemId(loginUser.getOemId());
                storeInfo.setEnterpriseId(enterpriseInfo.getId());
                this.storeInfoDao.insert(storeInfo);
            }else {
                storeInfo.setUpdatedBy(userId);

                this.storeInfoDao.update(storeInfo);
            }

        }else {
            return  ResultMessage.createFail("未找到该用户的商户信息，编辑失败");
        }

        return ResultMessage.createSuccess();
    }

    /**
     * 获取当前用户的门店
     * @param storeInfo
     * @return
     */
    @Override
    public ResultMessage getStores(StoreInfo storeInfo) {

        List<StoreInfo> storeInfos = this.storeInfoDao.queryByUserId(storeInfo);

        return ResultMessage.createSuccess(storeInfos);
    }

    /**
     * 添加门店详细信息
     *
     * @param loginUser
     * @param storeInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage addStoreDetailedInfo(UserInfo loginUser, StoreInfo storeInfo) {

        storeInfo.setUpdatedBy(loginUser.getId());
        storeInfoDao.insertStoreDetailedInfo(storeInfo);

        log.info("商家："+loginUser.getId()+"成功补充门店："+storeInfo.getName()+"详细信息");

        return ResultMessage.createSuccess();
    }

    /**
     * 升级普通门店成为优惠券门店
     *
     * @param id
     */
    @Override
    public ResultMessage upgradeStore(Integer id, UserInfo loginUser) {
        Integer count = storeInfoDao.getCount(loginUser.getId());
        if (count == 1) {
            return ResultMessage.createFail("暂时只支持一个优惠券门店!");
        }
        storeInfoDao.updateStoreInfoType(id);
        return ResultMessage.createSuccess("升级成功");
    }

    /**
     * 文件上传
     *
     * @param fileBytes
     * @param originalFilename
     * @param loginUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage fielUpload(byte[] fileBytes, String originalFilename, UserInfo loginUser,Integer storeId) {
        //获取oem商的oss配置信息
        log.info("开始上传门店图集userId{} 文件{}", loginUser.getId(), originalFilename);
        OemConfigInfo oemConfig = this.oemConfigInfoDao.getByOemId(loginUser.getOemId());
        if (oemConfig == null) {
            return ResultMessage.createFail();
        }
        //生成fielInfo和fullname
        FileInfo fileInfo = new FileInfo(oemConfig.getOemId(), loginUser.getId(), originalFilename, "");
        String fullName = fileInfo.createStoreFullName(oemConfig.getOemId());
        //推送到oss
        PutObjectResult putObjectResult = OSSUtils.putOSS(oemConfig.getEndPoint(), oemConfig.getAccessKeyId(), oemConfig.getAccessKeySecret(), oemConfig.getBucket(), fileInfo.getFullName(), fileBytes, true);
        if (null == putObjectResult) {
            log.error("上传失败oemid{} 文件{}", loginUser.getOemId(), originalFilename);
            return ResultMessage.createFail();
        }
        log.info("推送图片成功");
        fileInfo.setCreatedBy(loginUser.getId());
        fileInfo.setUpdatedBy(loginUser.getId());
        this.fileInfoDao.insert(fileInfo);
        String url = "http://" + oemConfig.getBucket() + "." + oemConfig.getEndPoint() + "/" + fullName;
        StoreMaterialInfo storeMaterialInfo = new StoreMaterialInfo();
        storeMaterialInfo.setStoreId(storeId);
        storeMaterialInfo.setFileId(fileInfo.getId().intValue());
        storeMaterialInfo.setCreatedBy(loginUser.getId());
        storeMaterialInfo.setUrl(url);
        storeMaterialInfoDao.insert(storeMaterialInfo);  //添加至关联表中
        return ResultMessage.createSuccess(url);
    }

    /**
     * 删除商家门店图片
     * @param storeId
     * @return
     */
    @Override
    public ResultMessage deleteStoreMaterialInfo(UserInfo loginUser,Integer storeId) {
        if(storeId == null){
            return ResultMessage.createFail("请刷新后重试!");
        }
        storeMaterialInfoDao.delete(storeId);
        log.info("商家"+loginUser.getId()+"成功清空门店"+storeId+"图片");
        return ResultMessage.createSuccess();
    }
}
